// src/app.ts
import express, {ErrorRequestHandler, NextFunction, Request, Response} from 'express'
import {config} from "./config/config";
import connectDB from "./db";
import logger, {console_level} from "./logger";
import {users_router} from "./routes/usersRouter";
import {games_router} from "./routes/gamesRouter";
import {client_router} from "./routes/clientRouter";
import {GamesModel} from "./models/gamesModel";
import {startUpdateToken} from "./services/tokenService";
import cors from 'cors';

require('express-async-errors');

process.on('unhandledRejection', (reason, promise) => {
    logger.fatal({msg: `错误被 process 捕获:`, data: promise, err: reason});
});


connectDB().then(() => {
    const app = express();
    app.use(express.json());
    app.use(cors());
    app.use(express.urlencoded({extended: false}));
    app.use('*', (req: Request, res: Response, next: NextFunction) => {
        const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
        const url = req.originalUrl;
        const method = req.method;
        const logInfo = {
            ip, url, method, body: null
        }
        if (method === 'POST') {
            logInfo.body = req.body;
        }
        logger.info({logInfo});
        next()
    });
    app.use('/client', client_router)// cocos游戏路由
    app.use('/games', games_router)//  games 文档路由
    app.use('/users', users_router)// users 文档路由
    app.get('/games_all', async (req: Request, res: Response) => {
        res.json(await GamesModel.find())
    });
    app.all('*', (req, res) => {
        res.status(404)
        res.json('not')
    })
    const errorHandler: ErrorRequestHandler = function (err, req, res, next) {
        try {
            logger.error(`center ${err.stack}`)
            res.status(500).send({err: err.stack});
        } catch (error) {
            res.status(500).send(err.stack);
        }
    };
    app.use(errorHandler)
    app.listen(config.port, "0.0.0.0", async () => {
        logger.info(`running ${config.port}, console_level: ${console_level}`);
        setInterval(startUpdateToken, 3600000);
    });
})
